<template>
    <div class="login">
        <div class="login-card">
            <div class="login-card-title">
                {{ title }}
            </div>
            <el-form :model="data.form" :rules="data.rules" ref="formRef" label-position="top">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="data.form.username" placeholder="请输入用户名" />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="data.form.password" type="password" show-password placeholder="请输入密码" />
                </el-form-item>
            </el-form>
            <div class="login-card-footer">
                <span class="login-card-footer-text">还没有账号？</span>
                <span class="login-card-footer-text active" @click="handleRegister">立即注册</span>
            </div>
            <el-button type="primary" style="width: 100%" @click="handleLogin">登录</el-button>
        </div>
        <RegisterModel ref="registerModelRef" />
    </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import RegisterModel from './components/registerModel.vue'
import { login } from '@/api/auth'
import { useRouter } from 'vue-router'
import { setStorage } from '@/utils/storage'

const router = useRouter()

const title = import.meta.env.VITE_TITLE
const data = reactive({
    form: {
        username: 'admin',
        password: 'admin123'
    },
    rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
    }
})

const formRef = ref(null)
const registerModelRef = ref(null)

const handleLogin = async () => {
    const valid = await formRef.value.validate()
    if (valid) {
        const res = await login(data.form)
        console.log(res)
        if (res.code === 200) {
            setStorage('TOKEN', res.data.access_token)
            setStorage('REFRESH_TOKEN', res.data.refresh_token)
            router.push('/')
        }
    }

}

const handleRegister = () => {
    registerModelRef.value.open()
}
</script>

<style scoped lang="scss">
.login {
    width: 100vw;
    height: 100vh;
    background: url('@img/login/bg.png') no-repeat center center;
    background-size: 100% 100%;
    box-sizing: border-box;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 80px;
    padding-bottom: 200px;
}

.login-card {
    width: 400px;
    background: rgba(255, 255, 255, 0.8);
    border-radius: 10px;
    padding: 20px;
    box-sizing: border-box;
}

.login-card-title {
    font-size: 24px;
    font-weight: bold;
    color: #333;
    text-align: center;
    margin-bottom: 40px;
}

.login-card-footer {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 20px;
}

.login-card-footer-text {
    color: #666;
}

.active {
    color: #409EFF;
    cursor: pointer;
    margin-left: 10px;
}
</style>